package cn.tedu.egarticle.controller;

import cn.tedu.egarticle.base.response.JsonResult;
import cn.tedu.egarticle.base.response.StatusCode;
import cn.tedu.egarticle.mapper.UserMapper;
import cn.tedu.egarticle.pojo.dto.UserArticleParam;
import cn.tedu.egarticle.pojo.dto.UserLoginParam;
import cn.tedu.egarticle.pojo.entity.Artivle;
import cn.tedu.egarticle.pojo.vo.ArtivleVo;
import cn.tedu.egarticle.pojo.vo.UserVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Validated
@RestController
@Tag(name = "用户模块")
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam param, HttpSession session) {
        log.debug("登录参数为={}", param);

        UserVo userVo = userMapper.selectByparm(param);

        if (userVo != null) {
            session.setAttribute("user", userVo);
            return JsonResult.ok(userVo);
        }
        return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);

    }

    @PostMapping("/article")
    @Operation(summary = "用户发布文章")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@RequestBody @Validated UserArticleParam param, HttpSession session) {
        log.debug("发布文章参数为={}", param);

        UserVo user = (UserVo) session.getAttribute("user");
        Artivle artivle = new Artivle();
        BeanUtils.copyProperties(param, artivle);

        artivle.setUserId(user.getId());

        int i = userMapper.insertArticle(artivle);
        if(i>0){
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.VALIDATED_ERROR);
    }

    @GetMapping("/selectByArticleId")
    @Operation(summary = "根据文章id查询文章详情")
    @ApiOperationSupport(order = 30)
    public JsonResult selectByArticleId(@RequestParam @Range(min = 1,max = 100,message = "文章ID要求在1-100之间") Integer id){
        ArtivleVo artivleVo = userMapper.selectByArticleId(id);
        if(artivleVo!=null){
            return JsonResult.ok(artivleVo);
        }
        return new JsonResult(StatusCode.VALIDATED_ERROR);
    }


}
